﻿using DllDependenciesAnalysis.DllAutoCompletions;
using DllDependenciesAnalysis.DllAutoCompletions.Business;
using DllDependenciesAnalysis.Helpers;
using NuGet.Repositories;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DllDependenciesAnalysis.AnalysisPlans.Business
{
    public class AutoCompletionDll : BaseAnalysisPlan
    {
        public string NugetLocalDir = "packages";

        public override void Analysis(AnalysisContent content)
        {
            var allErroNames = PrintDllMissDependency.AnalysisAllMissDependency(content.Path, content.SearchPaths?.ToArray());

            if (allErroNames?.Any() != true)
            {
                Console.WriteLine($"无法找到缺失或者版本不匹配的内容");
                return;
            }

            // 确认缺少的版本的内容
            if (allErroNames?.Any() == true)
            {
                /*  尝试还原内容
                 *      未知版本
                 *          需要判断手动选择还是直接使用最新的
                 *      尝试搜索是不是有匹配的直接存在的Dll
                 *      尝试搜索看看是不是存在其他的高于这个版本的版本
                 *          根据策略判断是需要自动找到最近的还是手动选择
                 *      完全找不到的，看看是不是存在于其他的Nuget里边了。全都还原之后，重新扫描
                 */
                var mappings = NugetHelper.GetShouldReductionVersion(allErroNames);

                var completions = new List<IAutoCompletion>
                {
                    new LocalNugetAutoCompletion(NugetLocalDir),
                };

                // 尝试添加全局的内容
                var globalPath = $@"C:\Users\{Environment.UserName}\.nuget\packages";
                if (Directory.Exists(globalPath))
                    completions.Add(new LocalNugetAutoCompletion(globalPath));

                var matchingStrategies = new[]
                {
                    MatchingStrategy.Complete,
                    MatchingStrategy.Closest,
                    MatchingStrategy.Latest,
                };

                foreach (var matchingStrategy in matchingStrategies)
                {
                    completions.Add(new RemoteNugetAutoCompletion(NugetLocalDir, matchingStrategy, NugetHelper.NugetUrl));
                }

                foreach (var mappintItem in mappings)
                {
                    var packageId = mappintItem.Key;
                    var version = mappintItem.Value;

                    foreach (var completion in completions)
                    {
                        var result = completion.Completion(content.Path, packageId, version);
                        if (result)
                            break;
                    }
                }
            }
        }
    }
}
